﻿#include "roledialog.h"
#include "ui_roledialog.h"

RoleDialog::RoleDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::RoleDialog)
{
    ui->setupUi(this);

    connect(ui->m_btnCancel, &QPushButton::clicked, this, &RoleDialog::on_cancel);
    connect(ui->m_btnSubmit, &QPushButton::clicked, this, &RoleDialog::on_submit);
}

RoleDialog::~RoleDialog()
{
    delete ui;
}

void RoleDialog::init(Role role)
{
    m_role = role;
    ui->m_rolename->setText(role.roleName);
}

void RoleDialog::on_cancel()
{
    reject();
}

void RoleDialog::on_submit()
{
    if(QMessageBox::question(this,
                             QString::fromLocal8Bit("提示"),
                             QString::fromLocal8Bit("请确认操作"),
                             QString::fromLocal8Bit("取消"),
                             QString::fromLocal8Bit("确认")) != 1)
    {
        return;
    }

    QSqlDatabase database = QSqlDatabase::database(DbUtil::SQLITE_CONNECTION_NAME, true);
    if (database.open())
    {
        QSqlQuery sql_query(database);
        if(m_role.op == "ADD")
        {
            QString sql = QString("insert into t_role(role_name) values('%1')")
                    .arg(ui->m_rolename->text());
            if(sql_query.exec(sql))
            {
                qDebug() << "insert t_role " << ui->m_rolename->text();
            }
        }

        if(m_role.op == "EDIT")
        {
            QString sql = QString("update t_role set role_name = '%1' where role_id = %2")
                    .arg(ui->m_rolename->text())
                    .arg(m_role.roleId);
            if(sql_query.exec(sql))
            {
                qDebug() << "update t_role " << ui->m_rolename->text();
            }
        }

    }
    accept();
}
